import 'package:custom_sliding_segmented_control/custom_sliding_segmented_control.dart';
import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_advanced_segment/flutter_advanced_segment.dart';
// import 'package:flutter_advanced_segment/flutter_advanced_segment_controller.dart';
import 'package:hexcolor/hexcolor.dart';

class DlSegment extends StatefulWidget {
  DlSegment({
    super.key,
    this.segments,
    this.onSegmentChange,
    this.backgroundColor = Colors.white,
    this.sliderColor = Colors.red,
  });
  Map<String, String>? segments;
  Function(int, String)? onSegmentChange;
  Color? backgroundColor;
  Color? sliderColor;
  @override
  State<DlSegment> createState() => _DlSegmentState();
}

class _DlSegmentState extends State<DlSegment> {
  // Create a controller
  final _selectedSegment = ValueNotifier('1pm');
  int _currentIndex = 0;

  Map<String, String> _segments = {
    '1pm': '1PM',
    '6pm': '6PM',
    '8pm': '8PM',
    'other': 'Others',
  };

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _segments = widget.segments ?? _segments;

    _selectedSegment.addListener(() {
      var value = _selectedSegment.value;
      var valueString = _segments[value];

      var keys = _segments.keys.toList();
      _currentIndex = keys.indexOf(value);

      //回调下标
      if (widget.onSegmentChange != null) {
        widget.onSegmentChange!(_currentIndex, valueString!);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40.0,
      decoration: BoxDecoration(
        // color: HexColor('#f5f5f5'),
        color: widget.backgroundColor,
        borderRadius: BorderRadius.circular(20.0),
      ),
      child: AdvancedSegment(
        controller: _selectedSegment,
        segments: _segments,
        activeStyle: const TextStyle(
          // TextStyle
          color: Colors.white,
          fontWeight: FontWeight.w600,
          fontSize: 15,
        ),
        inactiveStyle: TextStyle(
          // TextStyle
          color: DL_Config.DL_MainColor,
          fontWeight: FontWeight.w500,
          fontSize: 15,
        ),
        // backgroundColor: HexColor('#f5f5f5'), // Color
        backgroundColor: Colors.transparent.withOpacity(0.0),
        // sliderColor: HexColor('#ff3433'), // Color
        sliderOffset: 4.0, // Double
        borderRadius:
            const BorderRadius.all(Radius.circular(8.0)), // BorderRadius
        itemPadding: const EdgeInsets.symmetric(
          // EdgeInsets
          horizontal: 15,
          vertical: 10,
        ),
        sliderDecoration: BoxDecoration(
          color: widget.sliderColor,
          borderRadius: const BorderRadius.all(Radius.circular(16.0)),
        ),
        animationDuration: const Duration(milliseconds: 250), // Duration
      ),
    );
  }
}
